import type { AxiosError, AxiosResponse } from 'axios';

import {
    DEFAULT_REQUEST_ERROR_CODE,
    DEFAULT_REQUEST_ERROR_MSG,
    ERROR_STATUS,
    NETWORK_ERROR_CODE,
    NETWORK_ERROR_MSG
} from '@/config';

import { showErrorMsg } from './msg';

type ErrorStatus = keyof typeof ERROR_STATUS;

/** Axios 请求异常返回错误信息 */
export async function errorByAxios(error: AxiosError) {
    // 构建错误信息
    let errorResult = {
        code: DEFAULT_REQUEST_ERROR_CODE,
        msg: DEFAULT_REQUEST_ERROR_MSG,
        success: false
    } as Api.FailedResult;
    showErrorMsg(errorResult);
    return errorResult;
}

/** Axios 请求异常返回错误信息 */
export async function errorByAxiosResponse(error: AxiosResponse) {
    if (!window.navigator.onLine) {
        // 网路错误
        Object.assign(error, { code: NETWORK_ERROR_CODE, msg: NETWORK_ERROR_MSG });
    } else {
        // 请求成功的状态码非200的错误
        const errorCode: ErrorStatus = error.status as ErrorStatus;
        const msg = ERROR_STATUS[errorCode] || DEFAULT_REQUEST_ERROR_MSG;
        Object.assign(error, { type: 'http', code: errorCode, msg });
    }

    // 构建错误信息
    let errorResult = {
        code: DEFAULT_REQUEST_ERROR_CODE,
        msg: DEFAULT_REQUEST_ERROR_MSG,
        success: false
    } as Api.FailedResult;
    showErrorMsg(errorResult);
    return errorResult;
}

/** 正常请求返回错误并弹窗 */
export async function errorByResult(result: Api.FailedResult) {
    showErrorMsg(result);
    return result;
}
